package com.boot.main.shiro;

import com.boot.main.jwt.JwtFilter;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 给filter设置安全管理器
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        // 默认认证界面路径---当认证不通过时跳转
        shiroFilterFactoryBean.setLoginUrl("/login.jsp");
        // 添加自己的过滤器并且取名为jwt
        Map<String, Filter> filterMap = new HashMap<>();
        filterMap.put("jwt", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        // 配置系统受限资源
        Map<String, String> map = new HashMap<String, String>();
//        map.put("/index.jsp", "authc");   // 请求需要身份认证
        map.put("/v1/api/login","anon"); // 请求无须访问权限
        map.put("/v1/api/login/**","anon"); // 请求无须访问权限
        map.put("/v1/api/exportExcel","anon"); // 请求无须访问权限
        map.put("/v1/api/code","anon"); // 请求无须访问权限
        map.put("/v1/api/jscode2session", "anon");
        map.put("/login.jsp","anon");
        map.put("/v1/api/**", "jwt");
        map.put("/v1/api/products", "anon");
        map.put("/v1/api/product/**", "anon");
        map.put("/v1/api/blog/articles**", "anon");
        map.put("/v1/api/blog/article/**", "anon");
        map.put("/v1/api/blog/categorys**", "anon");
        map.put("/v1/api/blog/**", "anon");
        map.put("/v1/api/comment**", "anon");
        map.put("/v1/api/tags**", "anon");
        // 所有请求通过我们自己的过滤器
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }

    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(MyRealm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 给安全管理器设置realm
        securityManager.setRealm(realm);
        // 关闭shiro的session（无状态的方式使用shiro）
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        return securityManager;
    }
}
